package training;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_5_30Training {
    //找到离给定两个节点最近的节点
    public int closestMeetingNode(int[] edges, int node1, int node2) {
        if(node1 == node2){
            return node1;
        }
        int[] node01_edges = new int[edges.length];
        int[] node02_edges = new int[edges.length];
        int current = node1;
        int step = 1;
        while (current != -1 && node01_edges[current] == 0) {
            node01_edges[current] = step++;
            current = edges[current];
        }
        current = node2;
        step = 1;
        while (current != -1 && node02_edges[current] == 0) {
            node02_edges[current] = step++;
            current = edges[current];
        }
        int res = Integer.MAX_VALUE;
        int node = -1;
        for (int i = 0; i < node01_edges.length; i++) {
            if(node01_edges[i] != 0 && node02_edges[i] != 0){
                int max = Math.max(node01_edges[i], node02_edges[i]);
                if(res > max){
                    res = max;
                    node = i;
                }
            }
        }
        return node;
    }
}
